package com.a2v2.online.store.common.logger.impl;

import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;

import com.a2v2.online.store.common.logger.contract.ILogger;
import com.a2v2.online.store.common.logger.contract.LocalStorage;

public class FileLogger implements ILogger {
	final String FIELD_SEPERATOR = "#";
	String server_id =null;		
	
	public void logInfo(Class clazz, String message) {
		StringBuffer strMessage = messageBuilder(message);		
		writeToLog(Level.INFO, strMessage.toString(), clazz.getName(), null, false);
	}
	
	public void logError(Class clazz, String message, Throwable t) {
		StringBuffer strMessage = messageBuilder(message);
		writeToLog(Level.ERROR, strMessage.toString(), clazz.getName(), null, false);
	}

	public void logDebug(Class clazz, String message) {
		StringBuffer strMessage = messageBuilder(message);		
		writeToLog(Level.DEBUG, strMessage.toString(), clazz.getName(), null, false);
	}

	
	private StringBuffer messageBuilder(String message) {
		LocalStorage storage = LocalStorage.getInstance();
		//TODO
		String userID = "userId"; //storage.getUserID();
		String TrxID = "TrxID"; //storage.getTrxID();		
						
		StringBuffer strMessage = new StringBuffer();
		strMessage.append(server_id).append(FIELD_SEPERATOR);		
		if (userID!=null)
			strMessage.append(userID).append(FIELD_SEPERATOR);
		if (TrxID!=null)
			strMessage.append(TrxID).append(FIELD_SEPERATOR);
		strMessage.append(message);
		return strMessage;
	}
	/**
     * This method is used to write log.
     * @param logLevel the LogLevel
     * @param message the String
     * @param userName the String
     * @param messageOnNextLine the boolean
     * @return 
     */
	@SuppressWarnings("deprecation")
	private static void writeToLog(Level logLevel, String message, String module, String username, boolean messageOnNextLine) {
		String dataToWrite = Thread.currentThread().getName()
				+ "\t"
				+ ((username == null || username.equals("")) ? "<Unknown>"
						: username);
		if (messageOnNextLine)
			dataToWrite += "\r\n";
		else
			dataToWrite += "\t";
		dataToWrite += message;

		Logger log = LogManager.getLogger(module);
		if (logLevel == Level.OFF) {
		} else if (logLevel == Level.ERROR) {
			if (log.isEnabledFor(Priority.ERROR))
				log.error(dataToWrite);
		} else if (logLevel == Level.WARN) {
			if (log.isEnabledFor(Priority.WARN))
				log.warn(dataToWrite);
		} else if (logLevel == Level.INFO) {
			if (log.isEnabledFor(Priority.INFO))
				log.info(dataToWrite);
		} else if (logLevel == Level.DEBUG) {
			if (log.isEnabledFor(Priority.DEBUG))
				log.debug(dataToWrite);
		}
	}

}
